package admin_menu

import (
	"context"
	adminMenuApi "go-skeleton/api/admin/service/admin_menu"
	"go-skeleton/app/admin/service/internal/biz"
	"go-skeleton/pkg/util/tool"
	"google.golang.org/protobuf/types/known/emptypb"
)

type MenuService struct {
	adminMenuApi.UnimplementedMenuServiceServer

	m *biz.AdminMenuBiz
	r *biz.AdminRoleBiz
	u *biz.AdminUserBiz
}

func NewMenuService(m *biz.AdminMenuBiz, r *biz.AdminRoleBiz, u *biz.AdminUserBiz) *MenuService {
	return &MenuService{m: m, r: r, u: u}
}

func (s *MenuService) GetMenu(ctx context.Context, req *emptypb.Empty) (resp *adminMenuApi.GetMenuReply, err error) {
	userId := ctx.Value("user_id").(int64)
	userInfo, err := s.u.FindByID(ctx, userId)
	if err != nil {
		return
	}
	roles, err := s.r.FindByRoleKeys(ctx, userInfo.AuthRole)
	if err != nil {
		return
	}
	names := make([]string, 0)
	for _, role := range roles {
		names = append(names, role.MenuAuth...)
		names = append(names, role.BtnAuth...)
	}
	names = tool.StringSliceUniq(names)
	return s.m.GetMenu(ctx, names)
}

func (s *MenuService) GetMenuAll(ctx context.Context, req *emptypb.Empty) (resp *adminMenuApi.GetMenuReply, err error) {
	return s.m.GetMenuAll(ctx)
}

func (s *MenuService) AddMenu(ctx context.Context, req *adminMenuApi.MenuInfo) (resp *adminMenuApi.MenuInfo, err error) {
	return s.m.Save(ctx, req)
}

func (s *MenuService) EditMenu(ctx context.Context, req *adminMenuApi.MenuInfo) (resp *adminMenuApi.MenuInfo, err error) {
	return s.m.Update(ctx, req)
}

func (s *MenuService) DelMenu(ctx context.Context, req *adminMenuApi.MenuInfo) (resp *emptypb.Empty, err error) {
	return s.m.DelMenu(ctx, req.Id)
}
